import storage from '@/pages_nbst/utils/storage.js'
import {
	login as Login
} from "@/pages_nbst/api/auth.js"

function test() {
	console.log('123');
}

function toQueryString(obj) {
	if (obj instanceof Object) {
		let tmp = []
		Object.keys(obj).forEach(key => {
			tmp.push(key + '=' + obj[key])
		})
		return tmp.join('&')
	} else {
		return ''
	}
}

function resetData(target, source, excludes = []) {
	const temp = JSON.parse(JSON.stringify(source))
	Object.keys(target).forEach((key) => {
		if (temp.hasOwnProperty(key) && !excludes.includes(key)) {
			target[key] = temp[key]
		}
	})
}

function getToken() {
	return storage.get('token')
}

function setToken(token) {
	storage.set('token', token)
	console.log();
}

function login() {
	return new Promise((resolve, reject) => {
		if (getToken()) {
			// uni.checkSession().then(() => {
			// 	console.log('checkSession: success !!')
			// 	resolve()
			// }).catch(() => {
			// 	uni.login({
			// 		provider: 'weixin'
			// 	}).then(res => {
			// 		console.log('uni.login: ', res);
			// 		resolve(res)
			// 	}).catch(() => {
			// 		console.log('uni.login: fail')
			// 		reject()
			// 	})
			// })
			resolve()
		} else {
			uni.login({
				provider: 'weixin'
			}).then(res => {
				console.log('uni.login: ', res);
				Login(res.code).then(res => {
					console.log('login: ', res);
					setToken(res.token)
					resolve(res)
				}).catch(err => {
					console.log('login: fail', err)
					reject(err)
				})
			}).catch((err) => {
				console.log('uni.login: fail', err)
				reject(err)
			})
		}

	})
}

export default {
	test,
	resetData,
	toQueryString,
	getToken,
	setToken,
	login,
}